var myKey = 'e54c5a526d2aff5cce5132d90a95542f';
var userAgent = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36';
// Code for platform detection
var isMaterial = Framework7.prototype.device.ios === false;
var isIos = Framework7.prototype.device.ios === true;

// Add the above as global variables for templates
Template7.global = {
  material: isMaterial,
  ios: isIos,
};

// A template helper to turn time to 10-length
function pad2(number) {
  if (number <= 99) { number = ('0' + number).slice(-2); }
  return number;
}

function time10() {
  var d=new Date().getTime();
  var str = ("" + d).substr(0, 10);
  return str;
}

function fmtDate(ms) {
  var d = new Date();
  d.setTime(+(ms + "000"));
  var year = d.getUTCFullYear();
  var month = pad2(d.getUTCMonth() + 1);
  var day = pad2(d.getUTCDate());
  var h = pad2(d.getUTCHours());
  var m = pad2(d.getUTCMinutes());
  var s = pad2(d.getUTCSeconds());
  return year + '-' + month + '-' + day + ' ' + h + ':' + m + ':' + s;
}

// A stringify helper
// Need to replace any double quotes in the data with the HTML char
//  as it is being placed in the HTML attribute data-context
function stringifyHelper(context) {
  var str = JSON.stringify(context);
  return str.replace(/"/g, '&quot;');
}

function isFavorite(hashId) {
  var favoriteHashIds = localStorage.getItem('favoriteHashIds') || [];
  var index = favoriteHashIds.indexOf(hashId);
  if (index === -1) {
    return false;
  } else {
    return true;
  }
}

// Finally, register the helpers with Template7
// Template7.registerHelper('stringify', stringifyHelper);
// Template7.registerHelper('isFavorite', isFavorite);

// If we need to use custom DOM library, let's save it to $$ variable:
var $$ = Dom7;

if (!isIos) {
  // Change class
  // $$('.view.navbar-through').removeClass('navbar-through').addClass('navbar-fixed');
  // And move Navbar into Page
  $$('.pages.navbar-through').removeClass('navbar-through').addClass('navbar-fixed');
  $$('.view .navbar').prependTo('.view .page');
  // $$('.pages.navbar-fixed').removeClass('navbar-fixed');
}

// Initialize app
var myApp = new Framework7({
  material: isIos? false : true,
  template7Pages: true,
  precompileTemplates: true,
  modalTitle: '博君一笑',
  modalButtonOk: '确定',
  modalButtonCancel: '取消',
  notificationHold: 2000,
  notificationCloseOnClick: true,
  notificationCloseButtonText: '确定',
  swipeBackPage: true,
  animateNavBackIcon: true,
  onAjaxStart: function (xhr) {
    myApp.showIndicator();
  },
  onAjaxComplete: function (xhr) {
    myApp.hideIndicator();
  },
  // pushState: !!Framework7.prototype.device.os,
});

// Add view
var mainView = myApp.addView('.view-main', {
    // Because we want to use dynamic navbar, we need to enable it for this view:
    dynamicNavbar: true,
    // domCache: true,
});



// Night mode
function switchNightMode(isNightMode) {
  if (isNightMode) {
    $$('body').addClass('layout-dark').addClass('theme-lightblue').addClass('theme-bluegray');
    localStorage.setItem('nightMode', true);
  } else {
    $$('body').removeClass('layout-dark').removeClass('theme-lightblue').removeClass('theme-bluegray');
    localStorage.setItem('nightMode', false);
  }
}

var nightMode = JSON.parse(localStorage.getItem('nightMode'));
$$('#nightSwitch').prop('checked', nightMode);
switchNightMode(nightMode);

$$(document).on('change', '#nightSwitch', function() {
  var isNightMode = $$('#nightSwitch').prop('checked');
  switchNightMode(isNightMode);
});


// Prepare data
function prepareData() {
  var notFirst = JSON.parse(localStorage.getItem('notFirst'));
  if (notFirst !== true) {
    var txtRespData = JSON.parse('{"error_code": 0,"reason": "Success","result": {"data":[{"content":"我们厂今天有领导来检查，车间主任一再强调要把他们当空气！！认真干自己的活，不要去观望他们，结果领导来检查的时候，我一二B同事推着装工件的小车就冲视察领导撞过去了，直接撞领导腿上，当时那哥们就震惊了，说道“我靠，什么情况，是什么东西挡住我了吗？？”要不是我们陪同的经理拦着，那丫非要从那领导身上压过去","hashId":"9cb65138b5131e9f233b3b1c0e5f26a6","unixtime":1491033230,"updatetime":"2017-04-01 15:53:50"},{"content":"一刚毕业的同学去五百强面试招聘。 结果在面试交材料的时候不小心把面试官的手机碰到地上了。 面试官一脸无奈的表情，这时候，同学说：“考官，我赔你吧，现在没钱，就从我下个月的工资扣吧！” 然后他就进去了。","hashId":"5eeff288f62f8bdecc64f3060e9d2daf","unixtime":1491032030,"updatetime":"2017-04-01 15:33:50"},{"content":"今天下午在街上看到一哥们儿叼了支烟给对面的出租车招手，司机在车流中各种调头开到那哥们儿身旁，那哥们儿走到司机旁边说借个火先，司机借火完毕后，谁知那哥们儿竞然潇洒的走了，留下出租司机在车里凌乱了……还没完，半分钟后司机才下车骂了有一分钟……","hashId":"a18dbad6a31942ca1ece46fbbf83901f","unixtime":1491032030,"updatetime":"2017-04-01 15:33:50"},{"content":"某专家称：现在房价并不贵，胸罩比房子贵多了。好胸罩600元，面积仅为0.02平米。即一平米胸罩超过3万元。 按全国二三线城市商品房均价4000元计算，胸罩相当于房价7倍多。 如考虑胸罩使用期限只有一年，而商品房平均寿命约40年，胸罩实际价格相当于房价300倍。 可见，房价并不贵...","hashId":"38b254d31df73486f237fcb6a7d5e50e","unixtime":1491032030,"updatetime":"2017-04-01 15:33:50"},{"content":"我爸：你四叔他儿子，比你大一岁，人家上周买了个卡迪拉克。你买个自行车的钱都不够。 我：那卡迪拉克我四叔出了三十多万。 我爸：那不还有十几万自己出的吗。 我：那十几万丈母娘出的。 我爸：你TM连个对象都没有。 我。。。！","hashId":"6978722388886610fb0c7ee0b812bc38","unixtime":1491030830,"updatetime":"2017-04-01 15:13:50"},{"content":"哥们跟借我了300块钱， 今天突然说，我支付宝还欠你300块钱是吧？ 我说：是。 接下来他说：那样我把支付宝卸载了咱们就两清了。","hashId":"ce2f46de8dfcf366de38d1eab2394d40","unixtime":1491030830,"updatetime":"2017-04-01 15:13:50"},{"content":"一个人在公园里面发呆， 一男的来搭讪：“美女我给你一百块，你可不可以让我看一看你的胸？ 然后我收了钱，暴打了他一顿。 心想这年头怎么那么多奇葩，拿钱想看我凶！","hashId":"dd8cbef5c839dd9e9d8d14b853d882b8","unixtime":1491030830,"updatetime":"2017-04-01 15:13:50"},{"content":"客轮经过一个荒岛，远远看见岛上有个穿着兽皮，满面胡须的人，他一面狂叫一面挥手，游客问船长那是谁？船长不耐烦地说：不知道啊，每年我们的船开过这里，他都要发狂一次！","hashId":"a46533b5e035ca693bd99c0589074069","unixtime":1491030230,"updatetime":"2017-04-01 15:03:50"},{"content":"老师：小明，以后你同桌丽丽上课睡觉你提醒她一下。 小明：哦，知道了。 第二天刚上课，小明就对丽丽说：丽丽，你该睡觉啦！ 老师怕你忘了让我提醒你呢。","hashId":"59978236054269ba15864fc92042180d","unixtime":1491030230,"updatetime":"2017-04-01 15:03:50"},{"content":"小时候，每次在电视看排球比赛，我和我爸就赌穿什么颜色衣服的姑娘会赢，奇怪我每次都输给我爸。 后来有一次，我问我爸：“爸爸，右上角那个‘重播’是什么意思？” 记得他当时说：“专心看比赛，再问以后就不跟你赌了。”","hashId":"19dcaaecf7ad24a22146375cf7b761b0","unixtime":1491030230,"updatetime":"2017-04-01 15:03:50"}]}}');
    var imgRespData = JSON.parse('{"error_code": 0,"reason": "Success","result": {"data":[{"content":"从脖子到肚脐全是沟","hashId":"97501839222BE2E68592AE0CFF2223B3","unixtime":1488188421,"updatetime":"2017-02-27 17:40:21","url":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/joke/201702/27/97501839222BE2E68592AE0CFF2223B3.jpg"},{"content":"昨天有人说，李白太过分了，李白表示，其实我也很绝望的好嘛？","hashId":"BE7240069F6EF08CA48D178F7B62ED77","unixtime":1488188421,"updatetime":"2017-02-27 17:40:21","url":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/joke/201702/27/BE7240069F6EF08CA48D178F7B62ED77.jpg"},{"content":"你怎么画五角星？","hashId":"F9981CB5F70562E943F8C2081AD48AE8","unixtime":1488188421,"updatetime":"2017-02-27 17:40:21","url":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/joke/201702/27/F9981CB5F70562E943F8C2081AD48AE8.jpg"},{"content":"那就便宜一点吧，也不容易！","hashId":"AFBE1011C7628EC0C1FC9B92916A93CF","unixtime":1488188421,"updatetime":"2017-02-27 17:40:21","url":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/joke/201702/27/AFBE1011C7628EC0C1FC9B92916A93CF.jpg"},{"content":"你们都是这样宠媳妇的吗？","hashId":"24932F339DE04A6221B17865CA95A43B","unixtime":1488188421,"updatetime":"2017-02-27 17:40:21","url":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/joke/201702/27/24932F339DE04A6221B17865CA95A43B.gif"},{"content":"强迫症患者看完表示爽","hashId":"5BB3D0D944D9A365920DE1D20D54C8FF","unixtime":1488188421,"updatetime":"2017-02-27 17:40:21","url":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/joke/201702/27/5BB3D0D944D9A365920DE1D20D54C8FF.gif"},{"content":"我们都有降落伞","hashId":"8111B11AE9A968D03BC24C810FB17BC8","unixtime":1488188421,"updatetime":"2017-02-27 17:40:21","url":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/joke/201702/27/8111B11AE9A968D03BC24C810FB17BC8.gif"},{"content":"大家帮掌掌眼 戳出洞了没","hashId":"31D8C5ED5D3855A4E9A3F8507D002E8A","unixtime":1488188421,"updatetime":"2017-02-27 17:40:21","url":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/joke/201702/27/31D8C5ED5D3855A4E9A3F8507D002E8A.gif"},{"content":"战靴","hashId":"2DD9DF306D682C5E245D263F1361A648","unixtime":1488188421,"updatetime":"2017-02-27 17:40:21","url":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/joke/201702/27/2DD9DF306D682C5E245D263F1361A648.jpg"}]}}');
    localStorage.setItem('texts', JSON.stringify(txtRespData.result.data));
    localStorage.setItem('images', JSON.stringify(imgRespData.result.data));
    localStorage.setItem('notFirst', 'true');
  }
}
prepareData();


// Load Virtual List Data
var textList, imageList, favoriteList;
function loadVirtualLists() {
  var textData = JSON.parse(localStorage.getItem('texts')) || [];
  textList = myApp.virtualList('.text-list', {
    items: textData,
    height: 200,
    renderItem: function(index, item) {
      var isfav = isFavorite(item.hashId);
      var iconCls = isfav ? 'fa-heart' : 'fa-heart-o';
      return  '<li class="card">' +
                '<div class="card-content">' +
                  '<div class="card-content-inner">' +
                    '<p>' + item.content + '</p>' +
                  '</div>' +
                '</div>' +
                '<div class="card-footer no-border">' +
                  '<span>' + fmtDate(item.unixtime) + '</span>' +
                  '<span onclick="toggleFav(this);" class="star fa ' + iconCls + 
                  ' color-red" data-detail="' + stringifyHelper(item) + '"></span>' +
                '</div>' +
              '</li>';
    },
  });
  var imageData = JSON.parse(localStorage.getItem('images')) || [];
  imageList = myApp.virtualList('.image-list', {
    items: imageData,
    height: 500,
    dynamicHeightBufferSize: 10,
    renderItem: function(index, item) {
      var isfav = isFavorite(item.hashId);
      var iconCls = isfav ? 'fa-heart' : 'fa-heart-o';
      return  '<li class="card">' +
                '<div class="card-content">' +
                  '<div class="card-content-inner">' +
                    '<p>' + stringifyHelper(item.content) + '</p>' +
                    '<img src="' + item.url + '"/>' +
                  '</div>' +
                '</div>' +
                '<div class="card-footer no-border">' +
                  '<span>' + fmtDate(item.unixtime) + '</span>' +
                  '<span onclick="toggleFav(this);" class="star fa ' + iconCls + ' color-red" ' +
                  'data-detail="' + stringifyHelper(item) + '"></span>' +
                '</div>' +
              '</li>';
    },
  });
}
function loadFavriteVL() {
  var favoriteData = JSON.parse(localStorage.getItem('favorites')) || [];
  favoriteList = myApp.virtualList('.favorite-list', {
    items: favoriteData,
    height: function(item) {
      if(item.url) return 500;
      else return 180;
    },
    renderItem: function(index, item) {
      var isfav = isFavorite(item.hashId);
      var iconCls = isfav ? 'fa-heart' : 'fa-heart-o';
      var imgurl = "";
      if(item.url) {
        imgurl = '<img src="' + item.url + '">';
      }
      return  '<li class="card">' +
                '<div class="card-content">' +
                  '<div class="card-content-inner">' +
                    '<p>' + stringifyHelper(item.content) + '</p>' +
                    imgurl +
                  '</div>' +
                '</div>' +
                '<div class="card-footer no-border">' +
                  '<span>' + fmtDate(item.unixtime) + '</span>' +
                  '<span onclick="toggleFavAndUpd(this);" class="star fa ' + iconCls + ' color-red" ' +
                  'data-detail="' + stringifyHelper(item) + '"></span>' +
                '</div>' +
              '</li>';
    },
  });
}

loadVirtualLists();
loadFavriteVL();


// Navbar text
$$('#text-tab').on('show', function() {
  $$('#main-navbar-text').text('笑话');
});
$$('#image-tab').on('show', function() {
  $$('#main-navbar-text').text('趣图');
});
$$('#favorite-tab').on('show', function() {
  $$('#main-navbar-text').text('收藏');
  var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
  favoriteList.replaceAllItems(favorites);
});
$$('#setting-tab').on('show', function() {
  $$('#main-navbar-text').text('设置');
});


// toggle favrite
// in text and image page.
function toggleFav(e) {
  var item = JSON.parse($$(e)[0].dataset.detail);
  var hashId = item.hashId;
  var favoriteIds = JSON.parse(localStorage.getItem('favoriteHashIds')) || [];
  var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
  var idx = favoriteIds.indexOf(hashId);
  if (idx === -1) {
    favoriteIds.push(hashId);
    favorites.push(item);
    $$(e).removeClass('fa-heart-o').addClass('fa-heart');
  } else {
    favoriteIds.splice(idx, 1);
    favorites = favorites.filter(function(fave) {
      return fave.hashId !== hashId;
    });
    $$(e).removeClass('fa-heart').addClass('fa-heart-o');
  }
  localStorage.setItem('favoriteHashIds', JSON.stringify(favoriteIds));
  localStorage.setItem('favorites', JSON.stringify(favorites));
}
// in favorite page
function toggleFavAndUpd(e) {
  var item = JSON.parse($$(e)[0].dataset.detail);
  var hashId = item.hashId;
  var favoriteIds = JSON.parse(localStorage.getItem('favoriteHashIds')) || [];
  var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
  var idx = favoriteIds.indexOf(hashId);
  if (idx === -1) {
    favoriteIds.push(hashId);
    favorites.push(item);
    $$(e).removeClass('fa-heart-o').addClass('fa-heart');
  } else {
    favoriteIds.splice(idx, 1);
    favorites = favorites.filter(function(fave) {
      return fave.hashId !== hashId;
    });
    $$(e).removeClass('fa-heart').addClass('fa-heart-o');
  }
  localStorage.setItem('favoriteHashIds', JSON.stringify(favoriteIds));
  localStorage.setItem('favorites', JSON.stringify(favorites));
  loadVirtualLists();
}


// Clear localStorage dara
$$('.clearFav').on('click', function() {
  myApp.confirm('清除掉所有缓存数据吗?', '请确认', function() {
    localStorage.setItem('textHashIds', '[]');
    localStorage.setItem('imageHashIds', '[]');
    localStorage.setItem('favoriteHashIds', '[]');
    localStorage.setItem('texts', '[]');
    localStorage.setItem('images', '[]');
    localStorage.setItem('favorites', '[]');
    localStorage.setItem('notFirst', 'false');
    prepareData();
    loadVirtualLists();
    loadFavriteVL();
    myApp.alert('已清除!');
  });
});


// Pull to refresh content
var textContent = $$('#text-tab.pull-to-refresh-content');
textContent.on('refresh', function(e) {
  $$.ajax({
    dataType: 'json',
    data: {
      key: myKey,
    },
    processData: true,
    url: 'http://v.juhe.cn/joke/randJoke.php',
    success: function(respData) {
      if (respData.error_code !== 0) {
        myApp.pullToRefreshDone();
        myApp.addNotification({
          message: '加载出错!'
        });
      } else {
        var respTxtData = respData.result;
        var localTexts = JSON.parse(localStorage.getItem('texts')) || [];
        var myData = [];
        respTxtData.forEach(function(item) {
          var localTxtIds = JSON.parse(localStorage.getItem('textHashIds')) || [];
          var idx = localTxtIds.indexOf(item.hashId);
          if (idx === -1) {
            localTxtIds.push(item.hashId);
            localStorage.setItem('textHashIds', JSON.stringify(localTxtIds));
            myData.push(item);
          }
        });
        localTexts = myData.concat(localTexts);
        localStorage.setItem('texts', JSON.stringify(localTexts));
        textList.prependItems(myData);
        myApp.pullToRefreshDone();
        myApp.addNotification({
          message: '新增了' + myData.length + '条记录。'
        });
      }
    },
    error: function(xhr, err) {
      myApp.pullToRefreshDone();
      myApp.alert('请求数据出错啦!');
      console.log("Error on ajax call: " + err);
      console.log(JSON.stringify(xhr));
    }
  });
});

var imageContent = $$('#image-tab.pull-to-refresh-content');
imageContent.on('refresh', function(e) {
  $$.ajax({
    dataType: 'json',
    data: {
      'key': myKey,
      'type': 'pic'
    },
    processData: true,
    url: 'http://v.juhe.cn/joke/randJoke.php',
    success: function(respData) {
      if (respData.error_code !== 0) {
        myApp.pullToRefreshDone();
        myApp.addNotification({
          message: '加载出错!'
        });
      } else {
        var respImgData = respData.result;
        var localImages = JSON.parse(localStorage.getItem('images')) || [];
        var myData = [];
        respImgData.forEach(function(item) {
          var localImgIds = JSON.parse(localStorage.getItem('imageHashIds')) || [];
          var idx = localImgIds.indexOf(item.hashId);
          if (idx === -1) {
            localImgIds.push(item.hashId);
            localStorage.setItem('imageHashIds', JSON.stringify(localImgIds));
            myData.push(item);
          }
        });
        localImages = myData.concat(localImages);
        localStorage.setItem('images', JSON.stringify(localImages));
        imageList.prependItems(myData);
        myApp.pullToRefreshDone();
        myApp.addNotification({
          message: '新增了' + myData.length + '条记录。'
        });
      }
    },
    error: function(xhr, err) {
      myApp.pullToRefreshDone();
      myApp.alert('请求数据出错啦!');
      console.log("Error on ajax call: " + err);
      console.log(JSON.stringify(xhr));
    }
  });
});
